<?php
namespace app\index\controller;
use think\Controller;
class Login extends Controller
{
    private $obj;
    public function _initialize(){
        $this->obj=model('user');
    }
    
    /**
     * 登录
     * @return [type] [description]
     */
    public function login(){
        // echo "<script>alert('添加成功!')</script>";
        // echo "<script>alert('修改成功!')</script>";
        // echo "<script>alert('请选择类别!')</script>";
        // exit;
        // $this->success('请选择类别');
        // exit;
        if(request()->isPost()){
            //验证字段
            $validate = validate('user');
            $data=input('post.');
            if(!$validate->scene('login')->check($data)){
                $this->error($validate->getError());
            }
            //验证用户名是否存在
            $res=$this->obj->get(['username'=>$data['username']]);
            if(!$res){
                $this->error('用户名不存在');
            }
            if($res['password']!=md5($data['password'])){
                $this->error('密码不正确');
            }
            $this->obj->updataById(['last_login_time'=>time()],$res->id);
            //保存用户信息
            session('user',$res,'index');
            return $this->redirect('index/index');         
        }
        return $this->fetch();
    }
    /**
     * 用户注册
     */
    public function reg(){
        if (request()->isPost()) {
            $validate = validate('user');
            // var_dump(input('post.'));exit;
            $data['username']=input('post.username');
            $data['password']=md5(input('post.password'));
            $data['email']=input('post.email');
            $data['last_login_time']=time();
            //验证用户是否存在
            $name=$this->obj->column('username');
            // var_dump($name);exit;
            foreach ($name as $v) {
                // echo $data['title'];
                // echo '<br/>'.$v;exit;
                if(($data['username']==$v)){
                    exit($this->error('名称已经存在'));
                }
            }
            if(!$validate->check(input('post.'))){
                $this->error($validate->getError());
            }
            //添加数据
            if($this->obj->add($data)){
                $this->success('注册成功','login/login');
            }
        }
        return $this->fetch();
    }
    public function logout(){
        session(null,'index');
        $this->redirect('index/index');
    }
}
